package org.opentcs.kcvehicle.communication.kc.udp.agv.param;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import org.opentcs.kcvehicle.communication.kc.common.Package;
import org.opentcs.kcvehicle.communication.kc.common.byteutils.ByteUtil;
// import org.opentcs.kcvehicle.communication.kc.common.byteutils.ByteUtil;
// import org.opentcs.kcvehicle.communication.kc.common.byteutils.ByteUtil;

public class AgvEvent
    extends
      AgvEventHeader
    implements
      IAgvEvent,
      Serializable {
  private byte[] bodyLength;
  private byte[] retain;
  private byte[] body;

  //for Request
  //有content 传，没有content 传new byte[]
  public AgvEvent(Byte commandCode) {
    super(commandCode);
    //初始化
    bodyLength = new byte[]{0x00, 0x00};
    retain = new byte[]{0x00, 0x00};
    body = new byte[]{};
  }

  public AgvEvent(Byte commandCode, byte[] body) {
    super(commandCode);
    //初始化
    bodyLength = new byte[]{0x00, 0x00};
    retain = new byte[]{0x00, 0x00};
    if (commandCode.equals(AgvEventConstant.CommandCode_ISSUE_SUBSCRIPTION)) {
      //依据命令码 构建参数
      this.bodyLength = ByteUtil.shortToBytes((short) body.length);
      this.body = body;
    }
  }

  public void setBody(byte[] body) {
    this.bodyLength = ByteUtil.shortToBytes((short) body.length);
    this.body = body;
  }

  //for Response
  public AgvEvent(Byte serviceCode, Byte commandCode, Byte executionCode) {
    super(serviceCode, commandCode, executionCode);
  }

  @Override
  public Package toBytes() {
    List<Byte> headerBytes = getHeaderBytes();
    for (Byte b : bodyLength) {
      headerBytes.add(b);
    }
    for (Byte b : retain) {
      headerBytes.add(b);
    }
    for (Byte b : body) {
      headerBytes.add(b);
    }
    byte[] bytes = new byte[headerBytes.size()];
    for (int i = 0; i < headerBytes.size(); i++) {
      bytes[i] = headerBytes.get(i);
    }
    return new Package(bytes, getTransationIdString());
  }

  public String getTransationIdString() {
    return transationId[0] + "-" + transationId[1];
  }

  @Override
  public Package toBytes(Object newValue) {
    return null;
  }

  @Override
  public String toString() {
    return "AgvEvent{" +
        "Header=" + headerToString() +
        ", bodyLength=" + Arrays.toString(bodyLength) +
        ", body=" + Arrays.toString(body) +
        '}';
  }

  @Override
  public String protocolName() {
    return "";
  }
}
